package com.base.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.exception.MyException;
import com.base.redis.RedisUtil;
import com.base.sys.dto.SysUserQueryDTO;
import com.base.sys.dto.UserMenuPermissionDTO;
import com.base.sys.entity.SysUser;
import com.base.sys.entity.SysUserUpdateLog;
import com.base.sys.service.ISysUserService;
import com.base.sys.service.ISysUserUpdateLogService;
import com.base.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.ExecutionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.swing.StringUIClientPropertyKey;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gjj
 * @since 2018-11-23
 */
@RestController
@RequestMapping("/sys/sys-user")
public class SysUserController {


    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ObjectCompareUtil objectCompareUtil;

    @Autowired
    private ISysUserUpdateLogService sysUserUpdateLogService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private Seaweedfs seaweedfs;


    @RequestMapping("/list")
    @RequiresPermissions("employee:query")
    public Result list(@RequestBody SysUserQueryDTO sysUserQueryDTO){
        Integer page = sysUserQueryDTO.getPage();
        Integer limit = sysUserQueryDTO.getLimit();
        Page pageRequest=new Page(page,limit);
        QueryWrapper<SysUser> sysUserQueryWrapper = getWrapper(sysUserQueryDTO);
        IPage<SysUser> sysUserIPage = sysUserService.selectPageNew(pageRequest, sysUserQueryWrapper);
        return Result.successResult(sysUserIPage);
    }

    @RequestMapping("/export")
    @RequiresPermissions("employee:export")
    public void export(@RequestBody SysUserQueryDTO sysUserQueryDTO, HttpServletResponse response){
        QueryWrapper<SysUser> sysUserQueryWrapper = getWrapper(sysUserQueryDTO);
        List<SysUser> list = sysUserService.selectNew(sysUserQueryWrapper);
        MyExcelUtil.exportToFile(SysUser.class,list,response);
    }

    @RequestMapping("/import")
    @RequiresPermissions("employee:import")
    public Result importData(MultipartFile file)throws Exception {
        List<SysUser> list = MyExcelUtil.importFromFile(SysUser.class, file);
        for (SysUser sysUser:list){
            saveOrUpdate(sysUser);
        }
        return Result.successResult();
    }


    private QueryWrapper<SysUser> getWrapper(SysUserQueryDTO sysUserQueryDTO){
        QueryWrapper<SysUser> sysUserQueryWrapper=new QueryWrapper<SysUser>();
        String username = sysUserQueryDTO.getUsername();
        String name = sysUserQueryDTO.getName();
        if(!StringUtils.isEmpty(username)){
            sysUserQueryWrapper.like("webUser.USERNAME","%"+username+"%");
        }
        if(!StringUtils.isEmpty(name)){
            sysUserQueryWrapper.like("webUser.NAME","%"+name+"%");
        }
        return sysUserQueryWrapper;
    }

    @RequestMapping("/save-or-update")
    @RequiresPermissions("employee:edit")
    public Result saveOrUpdate(@RequestBody SysUser sysUser)throws Exception{
        String id = sysUser.getId();
        SysUser currentUser=(SysUser) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isEmpty(id)){
            //判断有无该用户名存在
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("username",sysUser.getUsername());
            int count = sysUserService.count(queryWrapper);
            if(count>0){
                return Result.errorResult("该用户名已存在");
            }
            queryWrapper=new QueryWrapper();
            queryWrapper.eq("name",sysUser.getName());
            count = sysUserService.count(queryWrapper);
            if(count>0){
                return Result.errorResult("该姓名已存在");
            }
            queryWrapper=new QueryWrapper();
            queryWrapper.eq("mobile",sysUser.getMobile());
            count = sysUserService.count(queryWrapper);
            if(count>0){
                return Result.errorResult("该手机号已存在");
            }
            queryWrapper=new QueryWrapper();
            queryWrapper.eq("email",sysUser.getEmail());
            count = sysUserService.count(queryWrapper);
            if(count>0){
                return Result.errorResult("该邮箱已存在");
            }

            sysUser.setCreateTime(new Date());
            //初始化密码为123456
            sysUser.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes("UTF-8")));
            //状态启用
            sysUser.setStatus(1);
            sysUser.setVersion(1);
        }else{
            SysUser dataSysUser = sysUserService.getById(id);
            String username = sysUser.getUsername();
            String name = sysUser.getName();
            String email = sysUser.getEmail();
            String mobile = sysUser.getMobile();
            if(!username.equals(dataSysUser.getUsername())){
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("username",username);
                int count = sysUserService.count(queryWrapper);
                if(count>0){
                    return Result.errorResult("该用户名已存在");
                }
            }
            if(!name.equals(dataSysUser.getName())){
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("name",name);
                int count = sysUserService.count(queryWrapper);
                if(count>0){
                    return Result.errorResult("该姓名已存在");
                }
            }
            if(!email.equals(dataSysUser.getEmail())){
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("email",email);
                int count = sysUserService.count(queryWrapper);
                if(count>0){
                    return Result.errorResult("该邮箱已存在");
                }
            }
            if(!mobile.equals(dataSysUser.getMobile())){
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("mobile",mobile);
                int count = sysUserService.count(queryWrapper);
                if(count>0){
                    return Result.errorResult("该手机号已存在");
                }
            }

            //插入修改记录
            String compare = objectCompareUtil.compare(dataSysUser, sysUser);
            if(!StringUtils.isEmpty(compare)){
                SysUserUpdateLog sysUserUpdateLog=new SysUserUpdateLog();
                sysUserUpdateLog.setOperateContent(compare);
                sysUserUpdateLog.setOperateTime(new Date());
                sysUserUpdateLog.setUserId(id);
                sysUserUpdateLog.setOperatePerson(currentUser.getUsername());
                sysUserUpdateLogService.save(sysUserUpdateLog);
            }


            String password = sysUser.getPassword();
            if(!StringUtils.isEmpty(password)){
                sysUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes("UTF-8")));
            }
            sysUser.setUpdateTime(new Date());
        }
        boolean b = sysUserService.saveOrUpdate(sysUser);
        if(!b){
            throw new RuntimeException();
        }
        return Result.successResult();
    }


    @RequestMapping("/assign-role")
    @RequiresPermissions("employee:assign")
    public Result assignRole(@RequestBody SysUser sysUser){
        Result result = sysUserService.assignRole(sysUser);
        return result;
    }



    @RequestMapping("/login")
    public Result login(@RequestBody SysUser sysUser, HttpServletRequest request){
        String username = sysUser.getUsername();
        String password = sysUser.getPassword();
        Boolean rememberMe = sysUser.getRememberMe();
        String code = sysUser.getCode();
        Cookie[] cookies = request.getCookies();
        String systemCode = null;
        for (Cookie c : cookies) {
            if (c.getName().equals("captchaCode")) {
                String uuidCode = c.getValue();
                systemCode = (String) redisUtil.get(uuidCode);
                break;
            }
        }
        if(StringUtils.isEmpty(systemCode)){
            return Result.errorResult("验证码已失效，请重新获取");
        }
        if(!code.equals(systemCode)){
            return Result.errorResult("验证码错误");
        }
        UsernamePasswordToken token=new UsernamePasswordToken();
        token.setUsername(username);
        token.setPassword(password.toCharArray());
        token.setRememberMe(rememberMe);
        Subject subject= SecurityUtils.getSubject();
        try{
            subject.login(token);
        }
        catch (AuthenticationException e){
            return Result.errorResult("用户名或密码不正确");
        }
        catch (MyException e){
            return Result.errorResult(e.getMessage());
        }
        return Result.successResult();
    }


    @RequestMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.successResult();
    }

    @RequestMapping("/user-info")
    public Result userInfo(){
        SysUser sysUser = (SysUser)SecurityUtils.getSubject().getPrincipal();
        SysUser dataSysUser = sysUserService.getById(sysUser.getId());
        if(!dataSysUser.getVersion().equals(sysUser.getVersion())){
            //有改过
            sysUser=dataSysUser;
        }
        String avatar = sysUser.getAvatar();
        if(!StringUtils.isEmpty(avatar)){
            avatar="http://"+seaweedfs.getHost()+":"+seaweedfs.getPort()+"/"+avatar;
            sysUser.setDealAvatar(avatar);
        }
        //获取该用户拥有的权限
        UserMenuPermissionDTO userMenuPermission = sysUserService.getUserMenuPermission(sysUser.getId());
        if(userMenuPermission==null){
            userMenuPermission=new UserMenuPermissionDTO();
        }
        sysUser.setUserMenuPermission(userMenuPermission);
        return Result.successResult(sysUser);
    }

    @RequestMapping("/use-status/{type}")
    @RequiresPermissions("employee:useStatus")
    public Result useStatus(@RequestBody List<SysUser> list,@PathVariable Integer type){
        for(SysUser sysUser:list){
            sysUser.setStatus(type);
        }
        boolean b = sysUserService.updateBatchById(list);
        if(!b){
            throw new RuntimeException();
        }
        return Result.successResult();
    }

    @RequestMapping("/load-log/{id}")
    @RequiresPermissions("employee:log")
    public Result loadLog(@PathVariable String id, @RequestBody PageQuery pageQuery){
        Integer page = pageQuery.getPage();
        Integer limit = pageQuery.getLimit();
        QueryWrapper<SysUserUpdateLog> queryWrapper=new QueryWrapper<SysUserUpdateLog>();
        queryWrapper.eq("USER_ID",id);
        queryWrapper.orderByDesc("OPERATE_TIME");
        Page pageRequest=new Page(page,limit);
        IPage sysUpdatePage = sysUserUpdateLogService.page(pageRequest, queryWrapper);
        return Result.successResult(sysUpdatePage);
    }

}
